import { createStore } from 'redux';

let token: String = "";
let access = {};

if (localStorage.token) {
    if (Number(localStorage.token_expires) > Date.now() / 1000) {
        token = localStorage.token;
        try {
            access = JSON.parse(localStorage.access);
        } catch (e) {
            access = {};
        }

    }
}


export default createStore((
    state: {
        token: String,
        access: {
            [key: string]: any
        }
    } = { token, access },
    action: {
        type: String, value: {
            [key: string]: any
        }
    }
) => {
    switch (action.type) {
        case 'set_token':
            const { token, token_expires, access } = action.value;

            localStorage.token = token;
            localStorage.token_expires = token_expires;
            localStorage.access = JSON.stringify(access);

            return { ...state, token, access };
        case 'clear_token':
            delete localStorage.token;
            delete localStorage.token_expires;
            delete localStorage.access;

            return { ...state, token: null, access: {} };
        default:
            return state;
    }
});
